package file

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"iot-base/auth/svc"
	"iot-base/auth/types"
	"iot-base/common/pic"
	"runtime"
	"strings"
)

var sysType = runtime.GOOS

func GetPic(c *gin.Context) {
	resp := types.NewResult(c)
	var result []pic.PICInfo
	var req types.ReqGetPic
	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types.ExceptionError, err.Error())
		return
	}

	totalDb := svc.Dao.GetDb()
	listDb := svc.Dao.GetDb()
	if req.StationId != "" {
		totalDb = totalDb.Where("station_id = ?", req.StationId)
		listDb = listDb.Where("station_id = ?", req.StationId)
	}
	if req.IpcId != "" {
		totalDb = totalDb.Where("ipc_id = ?", req.IpcId)
		listDb = listDb.Where("ipc_id = ?", req.IpcId)
	}
	if req.EndTime != "" && req.BeginTime != "" {
		totalDb = totalDb.Where("snap_time >= ? and snap_time <= ? ", req.BeginTime, req.EndTime)
		listDb = listDb.Where("snap_time >= ? and snap_time <= ? ", req.BeginTime, req.EndTime)
	}
	var total int64
	err = totalDb.Model(&pic.PICInfo{}).Count(&total).Error
	err = listDb.Limit(req.Size).Offset((req.Page - 1) * req.Size).Find(&result).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	for i := range result {
		fileName := strings.ReplaceAll(result[i].FileName, "api/pic/", "")
		result[i].FileName = "/cms/v1/file/img?s=" + fileName
	}
	resp.Success(gin.H{"total": total, "list": result})
	return
}

func ShowImg(c *gin.Context) {
	resp := types.NewResult(c)
	var req types.ReqShowImg
	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types.ExceptionError, err.Error())
		return
	}
	parts := strings.Split(req.FileName, "@")
	if len(parts) == 2 {
		dir := strings.ReplaceAll(parts[1], "-", "/")
		if sysType == "windows" {
			c.File(dir + "/" + parts[0])
		} else {
			tfilename := "/home/linaro/work/pic/" + dir + "/" + parts[0]
			c.File(tfilename)
		}
	} else {
		resp.ErrorCode(types.Fail, "文件名不合法")
	}
}
